<div id="addCustomerProductFormDiv" style="height: 100%"></div>
<script id="addCustomerProductFormContent" type="text/html">
  <form class="layui-form open-form" id="addCustomerProductForm" lay-filter="addCustomerProductForm">
      <div class="open-model">
          <div class="open-auto">
              <div class="open-details-title" style="margin-bottom: 20px;">客户与订单信息</div>
              <!--        <input name="id" disabled-->
              <!--               class="layui-input" type="hidden">-->
              <div class="layui-col-md3">
                  <div class="layui-form-item">
                      <label class="layui-form-label">客户名称</label>
                      <div class="layui-input-inline">
                          <select name="customerId"lay-search id="customerId" {{d.eventName=='detail'||d.eventName=='userAdd'?'disabled':''}}
                                  lay-filter="customerId"></select>
                      </div>
                  </div>
              </div>
              <div class="layui-col-md3">
                  <div class="layui-form-item">
                      <label class="layui-form-label">客户编码</label>
                      <div class="layui-input-inline">
                          <input type="text" name="id" disabled
                                 class="layui-input">
                      </div>
                  </div>
              </div>

              <div class="layui-col-md3">
                  <div class="layui-form-item">
                      <label class="layui-form-label">所属渠道</label>
                      <div class="layui-input-inline">
                          <input type="text" name="agentName"
                                 disabled
                                 class="layui-input">
                      </div>
                  </div>
              </div>
              <!-- 客户级别, 录入人, 录入时间 -->
              <div class="layui-col-md3">
                  <div class="layui-form-item">
                      <label class="layui-form-label">客户级别</label>
                      <div class="layui-input-inline">
                          <input type="text" name="agentCategoryName" disabled
                                 class="layui-input">
                      </div>
                  </div>
              </div>
              <!--        <div class="layui-col-md3">-->
              <!--            <div class="layui-form-item">-->
              <!--                <label class="layui-form-label">录入人</label>-->
              <!--                <div class="layui-input-inline">-->
              <!--                    <input type="text" name="salesmanName" disabled-->
              <!--                           class="layui-input">-->
              <!--                </div>-->
              <!--            </div>-->
              <!--        </div>-->
              <!--        <div class="layui-col-md3">-->
              <!--            <div class="layui-form-item">-->
              <!--                <label class="layui-form-label">录入时间</label>-->
              <!--                <div class="layui-input-inline">-->
              <!--                    <input type="text" name="createTime" id="createTime" disabled-->
              <!--                           class="layui-input">-->
              <!--                </div>-->
              <!--            </div>-->
              <!--        </div>-->
              <div class="layui-col-md3">
                  <div class="layui-form-item">
                      <label class="layui-form-label">客服代表</label>
                      <div class="layui-input-inline">
                          <input type="text" name="creatorName" disabled
                                 class="layui-input">
                      </div>
                  </div>
              </div>
              <div class="open-details-title" style="margin-bottom: 5px;">客户产品信息</div>
              <!-- {{# if(d.eventName!="detail"){ }} -->
              <button class="layui-btn" id="addTableData" style="margin-top: 15px;">添加客户物料</button>
              <!-- {{# } }} -->

              <table class="layui-table" id="customerProductsTable" lay-filter="customerProductsTable"></table>
          </div>
          <div class="layui-form-item text-right">
              <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
              <!-- 客服代表, 客户物料名称, 客户物料编码 -->
              <!-- 提交按钮 -->
              <!-- {{# if(d.eventName!='detail'){ }} -->
              <button class="layui-btn" lay-filter="addCustomerProductBtn" lay-submit>保存</button>
              <!-- {{# } }} -->
          </div>
      </div>
  </form>
</script>

<script type="text/html" id="barterTableBar">
  <button
    class="layui-btn layui-btn-danger layui-btn-xs"
    type="button"
    lay-event="del"
  >
    删除
  </button>
  <!--    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="detail">详情</button>-->
</script>
<script id="productTypeFormContent" style="padding: 20px" type="text/html">
  <div class="layui-form-item" style="margin-top: 20px;">
    <label class="layui-form-label">产品类型</label>
    <input
      id="addSelfCollectedGoodsProductCategoryName"
      name="addSelfCollectedGoodsProductCategoryName"
      type="hidden"
      lay-verify="required"
    />
    <input
      id="addSelfCollectedGoodsProductCategoryId"
      name="addSelfCollectedGoodsProductCategoryId"
      type="hidden"
      lay-verify="required"
    />
    <div class="layui-input-inline mr0" id="selectProductType"></div>
    <button class="layui-btn" id="confirm" style="margin-left: 10px;">
      确认
    </button>
  </div>
</script>
<script>
  layui.use(["form"], function () {
    $ = layui.jquery;
    var form = layui.form;
    var admin = layui.admin;
    var table = layui.table;
    var upload = layui.upload;
    var config = layui.config;
    var laytpl = layui.laytpl;
    let nowData = { ...parentData };
    let data = nowData.data;
    let productTypeList = [];
    admin.req(
      "enterprise/product/admin/productType/list",
      {
        nowData,
      },
      function (res) {
        productTypeList = res.data;
        console.log("res", res);
        table.reload("customerProductsTable");
      }
    );

    laytpl(addCustomerProductFormContent.innerHTML).render(
      { ...parentData },
      function (html) {
        $("#addCustomerProductFormDiv").html(html);
      }
    );

    if (data) {
      admin.req(
        "enterprise/sell/admin/order/getCustomers",
        {},
        async function (res) {
          const productUnitRes = await admin.reqPro(
            "enterprise/product/admin/productUnit/list",
            {
              limit: 999999,
            }
          );
          const productUnitList = productUnitRes.data;
          if (nowData.eventName == "edit" || nowData.eventName == "detail") {
            let list = res.data;
            admin.initDataSelect(
              list,
              {},
              "customerId",
              data.customerId,
              "客户名称",
              "customerName"
            );
            admin.req(
              "enterprise/sell/admin/customersInfo/list",
              {
                id: data.customerId,
              },
              function (res1) {
                if (res1.data.length > 0) {
                  form.val("addCustomerProductForm", res1.data[0]);
                }
              }
            );

            let data1 = JSON.parse(JSON.stringify(data.externalProductForm));
            data1 = data1.map((v) => {
              v._unitOptions = productUnitList.map((v1) => {
                return {
                  value: v1.id,
                  label: v1.name,
                };
              });
              return v;
            });
            console.log(123, data1);

            table.reload("customerProductsTable", { data: data1 });
          } else if (nowData.eventName == "userAdd") {
            let list = res.data;
            console.log(data);
            admin.initDataSelect(
              list,
              {},
              "customerId",
              data.id,
              "客户名称",
              "customerName"
            );
            admin.req(
              "enterprise/sell/admin/customersInfo/list",
              {
                id: data.contactId,
              },
              function (res1) {
                if (res1.data.length > 0) {
                  form.val("addCustomerProductForm", res1.data[0]);
                }
              }
            );
          }
        }
      );
    } else {
      admin.initDataSelect(
        "enterprise/sell/admin/order/getCustomers",
        {},
        "customerId",
        null,
        "客户名称",
        "customerName"
      );
    }
    form.on("select(customerId)", function (d) {
      form.val("addCustomerProductForm", {
        id: "",
        agentName: "",
        agentCategoryName: "",
        salesmanName: "",
        createTime: "",
        creatorName: "",
      });
      form.render("select");
      if (d.value) {
        admin.req(
          "enterprise/sell/admin/customersInfo/list",
          {
            id: d.value,
          },
          function (res) {
            if (res.data.length > 0) {
              form.val("addCustomerProductForm", res.data[0]);
            }
          }
        );
      }
    });
    table.render({
      elem: "#customerProductsTable",
      page: false,
      cols: [
        [
          {
            field: "cusSkuCode",
            title: "客户物料编码",
            templet: admin.setTableInput(
              "cusSkuCode",
              nowData.eventName == "detail"
            ),
          },
          {
            field: "cusProductName",
            title: "客户物料名称",
            templet: admin.setTableInput(
              "cusProductName",
              nowData.eventName == "detail"
            ),
          },

          {
            field: "cusProductSpec",
            title: "客户规格码",
            templet: admin.setTableInput(
              "cusProductSpec",
              nowData.eventName == "detail"
            ),
          },
          {
            field: "productDetailName",
            title: "内部物料料号",
            templet: (d) => {
              return d.productDetailName
                ? d.productDetailName
                : "未关联Sku料号";
            },
            hide: nowData.eventName != "detail",
          },
          {
            field: "proTypeId",
            title: "客户产品类型",
            templet: (d) => {
              return `<button class="layui-btn " type="button" lay-event="selectProductType">${
                d.proTypeName ? d.proTypeName : "请选择类型"
              }</button>`;
              // let options = []
              // if (productTypeList.length > 0) {
              //     options = productTypeList.map(v => {
              //         return {
              //             label: v.name,
              //             value: v.id
              //         }
              //     })
              // }
              // return admin.setTableSelect('proTypeId', options, nowData.eventName == 'detail', 'proTypeId')(d)
            },
          },
          {
            field: "proUnitId",
            title: "产品单位",
            templet: (d) => {
              if (d._unitOptions) {
                return admin.setTableSelect(
                  "proUnitId",
                  d._unitOptions,
                  nowData.eventName == "detail",
                  "proUnitId"
                )(d);
              } else {
                return admin.setTableSelect(
                  "proUnitId",
                  [],
                  nowData.eventName == "detail",
                  "proUnitId"
                )(d);
              }
            },
          },
          {
            field: "enclosure",
            title: "上传附件",
            templet: admin.setTableUpload(
              "enclosure",
              nowData.eventName == "detail"
            ),
          },
          {
            field: "hasPack",
            title: "是否需要包装",
            templet: admin.setTableSelect(
              "hasPack",
              [
                { value: true, label: "是" },
                {
                  value: false,
                  label: "否",
                },
              ],
              nowData.eventName == "detail"
            ),
          },
          {
            field: "packInstructions",
            title: "包装说明",
            templet: admin.setTableInput(
              "packInstructions",
              nowData.eventName == "detail"
            ),
          },
          {
            field: "hasTreatment",
            title: "是否需要表面处理",
            templet: admin.setTableSelect(
              "hasTreatment",
              [
                { value: true, label: "是" },
                {
                  value: false,
                  label: "否",
                },
              ],
              nowData.eventName == "detail"
            ),
          },
          {
            field: "treatmentInstructions",
            title: "表面处理说明",
            templet: admin.setTableInput(
              "treatmentInstructions",
              nowData.eventName == "detail"
            ),
          },
          {
            align: "center",
            toolbar: "#barterTableBar",
            title: "操作",
            fixed: "right",
            hide: nowData.eventName == "detail",
          },
        ],
      ],
      data: [
        {
          cusProductName: "",
          cusSkuCode: "",
          cusProductSpec: "",
          cusProductType: "",
          enclosure: "",
          enclosureName: "",
          hasPack: "",
          packInstructions: "",
          hasTreatment: "",
          treatmentInstructions: "",
        },
      ],
      done: function (data) {
        $(".layui-table-body").css("overflow", "visible");
        $(".layui-table-box").css("overflow", "visible");
        $(".layui-table-view").css("overflow", "visible");
        admin.tableInputChange("customerProductsTable");
        admin.tableSelectChange(
          "customerProductsTable",
          "proTypeId",
          (index, value, list) => {
            admin.req(
              "enterprise/product/admin/productUnit/list",
              { productType: value },
              function (res) {
                const unitOptions = res.data.map((item) => ({
                  value: item.id,
                  label: item.name,
                }));
                list[index]._unitOptions = unitOptions;
                table.reload("customerProductsTable", { data: list });
              }
            );
          }
        );
        admin.tableSelectChange("customerProductsTable", "proUnitId");

        // form.on('select(proTypeId)', function (d) {
        //     console.log(222222)
        //     //
        //     // table.reload('customerProductsTable',{data:table.cache['customerProductsTable']})
        //     admin.req('enterprise/product/admin/productUnit/list', {productType: d.value}, function (res) {
        //         const unitOptions = res.data.map(item => ({
        //             value: item.id,
        //             label: item.name
        //         }));
        //         console.log(111,d)
        //         // 更新当前行数据源的缓存
        //         const index = $(d.elem).data('index');
        //         const tableData = table.cache['customerProductsTable']; // 替换为实际表格的 ID
        //         tableData[index]._unitOptions = unitOptions;
        //         console.log(111,tableData)
        //         // 更新表格重新渲染
        //         // table.reload('customerProductsTable', { data: tableData });
        //     })
        // })
        upload.render({
          elem: ".upload-btn", // 绑定上传按钮
          url: config.upload_url + "uploadFile",
          accept: "file", // 可接受的文件类型
          headers: { Authorization: "Bearer " + config.getToken() },
          done: function (res, index, upload) {
            // 上传成功的回调
            if (res.code === 200) {
              // 更新表格缓存中的数据
              const button = $(this.item);
              const index = button.data("index");
              let tableData = table.cache["customerProductsTable"];
              let rowIndex = tableData.findIndex(
                (v) => v["LAY_TABLE_INDEX"] == index
              );
              if (rowIndex > -1) {
                tableData[rowIndex].enclosure = res.data.url; // 假设接口返回的文件路径是 res.data.fileUrl
                tableData[rowIndex].enclosureName = res.data.fileName; // 假设接口返回的文件路径是 res.data.fileUrl
              }
              $(`#uploaded-${index}`).html(
                `<a href="${res.data.url}" target="_blank">查看附件</a>`
              );
              console.log("文件上传成功:", res.data);
            } else {
              console.error("文件上传失败:", res.message);
            }
          },
          error: function () {
            // 上传失败的回调
            console.error("上传失败");
          },
        });
      },
    });

    table.on("edit(customerProductsTable)", function (obj) {
      const { value, data, field } = obj; // 获取编辑的值、整行数据、字段名
      console.log("Edited field:", field);
      console.log("New value:", value);
      console.log("Updated row:", data);
    });
    table.on("tool(customerProductsTable)", function (obj) {
      var data = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      let list = table.cache["customerProductsTable"];
      const index = $(obj.tr[0]).data("index");

      if (layEvent == "del") {
        list = list.filter((v) => {
          return v["LAY_TABLE_INDEX"] != index;
        });
        table.reload("customerProductsTable", {
          data: list,
        });
      } else if (layEvent == "selectProductType") {
        let indexForm = admin.formOpen({
          area: ["500PX", "300PX"],
          offset: "25%",
          title: "选择产品类型",
          content: $("#productTypeFormContent").html(),
          success: function () {
            admin.initDataSelectTree(
              true,
              "enterprise/product/admin/productType/getAllTreeData",
              null,
              "selectProductType",
              null,
              "物料分类",
              "addSelfCollectedGoodsProductCategoryId",
              (d, xmSelectInstance) => {
                console.log(d);
                if (d.arr.length > 0) {
                  $("#addSelfCollectedGoodsProductCategoryName").val(
                    d.arr[0].name
                  );
                }
              }
            );
          },
        });
        $("#confirm").click(() => {
          const addSelfCollectedGoodsProductCategoryId = $(
            "#addSelfCollectedGoodsProductCategoryId"
          ).val();
          const addSelfCollectedGoodsProductCategoryName = $(
            "#addSelfCollectedGoodsProductCategoryName"
          ).val();
          list[index].proTypeId = addSelfCollectedGoodsProductCategoryId;
          list[index].proTypeName = addSelfCollectedGoodsProductCategoryName;

          admin.req(
            "enterprise/product/admin/productUnit/list",
            {
              productType: addSelfCollectedGoodsProductCategoryId,
              page: 1,
              limit: 10000,
            },
            function (res) {
              const unitOptions = res.data.map((item) => ({
                value: item.id,
                label: item.name,
              }));
              // 更新当前行数据源的缓存
              // const index = $(d.elem).data("index");
              // const tableData = table.cache["customerProductsTable"]; // 替换为实际表格的 ID
              list[index]._unitOptions = unitOptions;
              console.log(111, list);
              // 更新表格重新渲染
              // table.reload('customerProductsTable', { data: tableData });
              table.reload("customerProductsTable", {
                data: list,
              });
              layer.close(indexForm);
            }
          );

          return false;
        });
      }
      return false;
    });

    $("#addTableData").click(function () {
      let list = table.cache["customerProductsTable"];
      list.unshift({
        cusProductName: "",
        cusSkuCode: "",
        cusProductSpec: "",
        cusProductType: "",
        enclosure: "",
        enclosureName: "",
        hasPack: "",
        packInstructions: "",
        hasTreatment: "",
        treatmentInstructions: "",
      });
      table.reload("customerProductsTable", {
        data: list,
      });
      return false;
    });

    // 监听提交
    form.on("submit(addCustomerProductBtn)", function (d) {
      const formData = { ...d.field };
      let list = table.cache["customerProductsTable"];
      formData.externalProductForm = list;
      if (data) {
        formData.id = data.id;
      }
      let url = "";
      let method = "";
      if (data) {
        if (nowData.eventName == "userAdd") {
          url = "enterprise/sell/admin/customerProductCatalog/addProduct";
          method = "POST";
        } else {
          url = "enterprise/sell/admin/customerProductCatalog/update";
          method = "PUT";
        }
      } else {
        url = "enterprise/sell/admin/customerProductCatalog/addProduct";
        method = "POST";
      }

      admin.req(
        url,
        JSON.stringify(formData),
        function (res) {
          layer.closeAll("page");
          table.reload("customerProductCatalogTable");
        },
        method,
        true,
        "application/json; charset=utf-8"
      );
      return false;
    });
  });
</script>

<style>
  .layui-form-label {
    width: 120px;
  }

  #addCustomerProductForm .layui-table-cell {
    overflow: visible !important;
  }
</style>
